﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Text;
using System.IO;

namespace com.instalinks.android.web.web2sms
{
    /// <summary>
    /// Summary description for C2DMService
    /// </summary>
    [WebService(Namespace = "https://ssl.mgupta.me/web2sms/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class C2DMService : System.Web.Services.WebService
    {
        private const string GOOGLE_AUTH_URL = "https://www.google.com/accounts/ClientLogin";
        private const string C2DM_URL = "http://android.clients.google.com/c2dm/send";

        private const string AUTH = "authentication";
        private const string UPDATE_CLIENT_AUTH = "Update-Client-Auth";
        private const string PARAM_REGISTRATION_ID = "registration_id";
        private const string PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
        private const string PARAM_COLLAPSE_KEY = "collapse_key";
        private const string UTF8 = "UTF-8";

        [WebMethod]
        public string Notify(String auth_token, String registrationId, String mode, String appId, 
            String field1, String field2, String field3, String field4)
        {
            StringBuilder postData = new StringBuilder();

            //mode = ConvertUnicodeToAscii(mode);
            field1 = ConvertUnicodeToAscii(field1);
            //field2 = ConvertUnicodeToAscii(field2);
            //field3 = ConvertUnicodeToAscii(field3);

            postData.Append(PARAM_REGISTRATION_ID).Append("=").Append(registrationId);
            postData.Append("&").Append(PARAM_COLLAPSE_KEY).Append("=").Append("0");
            postData.Append("&").Append(PARAM_DELAY_WHILE_IDLE).Append("=").Append("0");

            postData.Append("&").Append("data.mode").Append("=").Append(mode);
            postData.Append("&").Append("data.appid").Append("=").Append(appId);
            postData.Append("&").Append("data.field1").Append("=").Append(field1);
            postData.Append("&").Append("data.field2").Append("=").Append(field2);
            postData.Append("&").Append("data.field3").Append("=").Append(field3);
            postData.Append("&").Append("data.field4").Append("=").Append(field4);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(C2DM_URL);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            webRequest.ContentLength = postData.ToString().Length;
            webRequest.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + auth_token);

            StreamWriter writer = null;
            try
            {
                writer = new StreamWriter(webRequest.GetRequestStream());
                writer.Write(postData.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            String result = webResponse.StatusDescription;
            webResponse.Close();

            return result;
	    }

        public String ConvertUnicodeToAscii(String unicodeStr)
        {
            byte[] asciiBytes = Encoding.Convert(Encoding.Unicode, Encoding.ASCII, Encoding.Unicode.GetBytes(unicodeStr));
            char[] asciiChars = new char[Encoding.ASCII.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
            Encoding.ASCII.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
            string asciiString = new string(asciiChars);

            return asciiString;
        }

        [WebMethod]
        public string GetAuthToken(String email, String password)
        {

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(GOOGLE_AUTH_URL);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";

            StringBuilder postData = new StringBuilder();
            postData.Append("Email=").Append(email);
            postData.Append("&Passwd=").Append(password);
            postData.Append("&accountType=GOOGLE");
            postData.Append("&source=Instalinks_Web2SMS");
            postData.Append("&service=ac2dm");

            webRequest.ContentLength = postData.ToString().Length;

            StreamWriter writer = null;
            try
            {
                writer = new StreamWriter(webRequest.GetRequestStream());
                writer.Write(postData.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader reader = new StreamReader(webResponse.GetResponseStream());

            String line = null;
            String auth_key = null;
            while ((line = reader.ReadLine()) != null)
            {
                if (line.StartsWith("Auth="))
                {
                    auth_key = line.Substring(5);
                }
            }

            webResponse.Close();
            return auth_key;
        }
    }
}
